﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Distribution.Service;
using Entities;

namespace DistributionApplication
{
    public enum EditorMode
    {
        New,
        Update,
        Duplicate,
        None
    }

    public partial class frmDistributionEditor : frmBase
    {
        #region - Properties -

        public EPole PoleToBeLoaded {get;set;}
        private bool controlsLoaded = false;
        public EditorMode Mode {get;set;}

        #endregion

        #region - Constructor -

        public frmDistributionEditor()
        {
            InitializeComponent();

            if (Settings.DistributionApplicationMode == DistributionApplicationMode.GPS)
            {
                tbcDistribution.TabPages.RemoveAt(1);
                tbcDistribution.SelectedIndexChanged += this.tbcDistribution_GPSSelectedIndexChanged;
            }
            else
                tbcDistribution.SelectedIndexChanged += this.tbcDistribution_InspectionSelectedIndexChanged;
        }

        #endregion

        #region - Event handlers -

        private void frmDistributionEditor_Load(object sender, EventArgs e)
        {
            Title = "PPI | Distribution Locating";
            camControl.TempPhotoFileName = "Photo";
            arTop.ComboStyle = ComboBoxStyle.DropDown;

            if (!controlsLoaded) 
            {
                InitializaControls();
                InitializeGPSPositionViewer();
                LoadCombos();

                controlsLoaded = true;
            }

            if (PoleToBeLoaded != null) 
            {
                ResetControls();
                LoadPole(PoleToBeLoaded);
            }
        }

        protected override void lblClose_Click(object sender, EventArgs e)
        {
            camControl.DisableCamera();
            Close();
        }

        private void tbcDistribution_InspectionSelectedIndexChanged(object sender, EventArgs e)
        {
            switch (tbcDistribution.SelectedIndex)
            {
                case 0:
                    camControl.DisableCamera();
                    LButtonText = "Next";
                    RButtonText = "Cancel";
                    break;
                case 1:
                    camControl.DisableCamera();
                    LButtonText = "Next";
                    RButtonText = "Cancel";
                    break;
                case 2:
                    camControl.DisableCamera();
                    LButtonText = "Next";
                    RButtonText = "Cancel";
                    break;
                case 3:
                    camControl.DisableCamera();
                    LButtonText = "Save";
                    RButtonText = "Cancel";
                    break;
                case 4:
                    LButtonText = "Save";
                    RButtonText = "Cancel";

                    if (Mode != EditorMode.Duplicate) 
                    {
                        if ((PoleToBeLoaded == null || PoleToBeLoaded.Images == null || PoleToBeLoaded.Images.Count == 0) && camControl.GetTakenImages().Count == 0)
                            camControl.ActiveCamera();
                    }
                    else 
                        camControl.ActiveCamera();

                    break;
                default:
                    break;
            }
        }

        private void tbcDistribution_GPSSelectedIndexChanged(object sender, EventArgs e)
        {
            switch (tbcDistribution.SelectedIndex)
            {
                case 0:
                    camControl.DisableCamera();
                    LButtonText = "Next";
                    RButtonText = "Cancel";
                    break;
                case 1:
                    camControl.DisableCamera();
                    LButtonText = "Next";
                    RButtonText = "Cancel";
                    break;
                case 2:
                    camControl.DisableCamera();
                    LButtonText = "Next";
                    RButtonText = "Cancel";
                    break;
                case 3:
                    camControl.DisableCamera();
                    LButtonText = "Next";
                    RButtonText = "Cancel";
                    break;
                case 4:
                    LButtonText = "Save";
                    RButtonText = "Cancel";

                    if (Mode != EditorMode.Duplicate)
                    {
                        if (PoleToBeLoaded == null || PoleToBeLoaded.Images == null || PoleToBeLoaded.Images.Count == 0)
                            camControl.ActiveCamera();
                    }
                    else
                        camControl.ActiveCamera();

                    break;
                default:
                    break;
            }
        }

        protected override void lblRButton_Click(object sender, EventArgs e)
        {
            camControl.DisableCamera();
            Close();
        }

        protected override void lblLButton_Click(object sender, EventArgs e)
        {
            switch (tbcDistribution.SelectedIndex)
            {
                case 0:
                    tbcDistribution.SelectedIndex = 1;
                    break;
                case 1:
                    tbcDistribution.SelectedIndex = 2;
                    break;
                case 2:
                    tbcDistribution.SelectedIndex = 3;
                    break;
                case 3:
                case 4:
                    //if (ValidateData())
                    //{
                    SaveDistributionResult();
                    camControl.DisableCamera();
                    Close();
                    //}
                    break;
                default:
                    break;
            }
        }

        private void txtInspBy_GotFocus(object sender, EventArgs e)
        {
            iplKeyboard.Enabled = true;
        }

        private void txtNumber_GotFocus(object sender, EventArgs e)
        {
            iplKeyboard.Enabled = true;
        }

        private void txtInspBy_LostFocus(object sender, EventArgs e)
        {
            iplKeyboard.Enabled = false;
        }

        private void txtNumber_LostFocus(object sender, EventArgs e)
        {
            iplKeyboard.Enabled = false;
        }

        private void txtComments_LostFocus(object sender, EventArgs e)
        {
            iplKeyboard.Enabled = false;
        }

        private void txtComments_GotFocus(object sender, EventArgs e)
        {
            iplKeyboard.Enabled = true;
        }

        private void txtCircuit_GotFocus(object sender, EventArgs e)
        {
            iplKeyboard.Enabled = true;
        }

        private void txtCircuit_LostFocus(object sender, EventArgs e)
        {
            iplKeyboard.Enabled = false;
        }

        #endregion

        #region - Private methods -

        private void InitializeGPSPositionViewer()
        {
            pGPSViewer.Gps = m_GPS;
            pGPSViewer.RefreshPosition();            
        }

        private void LoadCombos()
        {
            ddlMapSection.LoadDropDowns();
            assignNotes1.LoadCombos();

            List<ELookUp> classes = LLookUpService.GetAll(LookUpType.Class);
            MobileUIHelper.FillDropdown(ddlClasses, classes.ToArray(), "[None]");

            List<ELookUp> species = LLookUpService.GetAll(LookUpType.Species);
            MobileUIHelper.FillDropdown(ddlSpecies, species.ToArray(), "[None]");

            List<ELookUp> treatments = LLookUpService.GetAll(LookUpType.Treatment);
            MobileUIHelper.FillDropdown(ddlTreatments, treatments.ToArray(), "[None]");

            List<ELookUp> inspectionTypes = LLookUpService.GetAll(LookUpType.InspectionType);
            MobileUIHelper.FillDropdown(ddlInspection, inspectionTypes.ToArray(), "[None]");

            List<ELookUp> resultTypes = LLookUpService.GetAll(LookUpType.ResultType);
            MobileUIHelper.FillDropdown(ddlResult, resultTypes.ToArray(), "[None]");

            List<ELookUp> lengths = LLookUpService.GetAll(LookUpType.Length);
            MobileUIHelper.FillDropdown(ddlLengths, lengths.ToArray(), "[None]");

            MobileUIHelper.FillNumericCombo(ddlYears, DateTime.Now.Year, DateTime.Now.Year - 100, 1, true, "[None]");

            MobileUIHelper.FillNumericCombo(ddlLastVisit, DateTime.Now.Year, DateTime.Now.Year - 100, 1, true, "[None]");
            MobileUIHelper.FillNumericCombo(ddlGuardsQuantity, 1, 8, 1, true, "[Quantity]");

            List<ETransformerLookUp> kvs = LLookUpService.GetAll(TransformerLookUpType.Kv);
            MobileUIHelper.FillDropdown(ddlKv, kvs.ToArray(), "[None]");

            List<ETransformerLookUp> cType = LLookUpService.GetAll(TransformerLookUpType.ConductorType);
            MobileUIHelper.FillDropdown(ddlConductorType, cType.ToArray(), "[None]");

            List<ETransformerLookUp> acsrs = LLookUpService.GetAll(TransformerLookUpType.ACSR);
            MobileUIHelper.FillDropdown(ddlACSR, acsrs.ToArray(), "[None]");
        }

        private void InitializaControls()
        {
            List<ELookUp> phases = LLookUpService.GetAll(LookUpType.Phase);
            arPhase.Description = "Phase";
            arPhase.LoadEntities(phases, "Value", "Text", "[None]");

            List<ELookUp> tops = LLookUpService.GetAllTops();
            arTop.Description = "Top";
            arTop.ControlIfEntityExists = false;
            arTop.LoadEntities(tops, "Value", "Text", "[None]");

            RButtonText = "Cancel";
            LButtonText = "Next";
        }

        private void SaveDistributionResult()
        {
            EPole pole = new EPole();

            pole.Map = ddlMapSection.GetMap();
            pole.Section = ddlMapSection.GetSection();
            pole.Phases = arPhase.GetSelected();
            pole.Tops = arTop.GetSelected();

            pole.Specie = ddlSpecies.SelectedItem as ELookUp;
            pole.Class = ddlClasses.SelectedItem as ELookUp;
            pole.Treatment = ddlTreatments.SelectedItem as ELookUp;
            pole.Length = ddlLengths.SelectedItem as ELookUp;
            pole.Kv = ddlKv.SelectedItem as ETransformerLookUp;
            pole.ConductorType = ddlConductorType.SelectedItem as ETransformerLookUp;
            pole.ACSR = ddlACSR.SelectedItem as ETransformerLookUp;

            if (pGPSViewer.Latitude != Double.MinValue)
                pole.Latitude = pGPSViewer.Latitude;

            if (pGPSViewer.Longitude != Double.MinValue)
                pole.Longitude = pGPSViewer.Longitude;

            pole.InspBy = txtInspBy.Text.Trim();
            pole.Number = txtNumber.Text.Trim();
            pole.Circuit = txtCircuit.Text.Trim();
            if (ddlYears.SelectedIndex > 0)
                pole.Year = (Int32)ddlYears.SelectedItem;
            else
                pole.Year = Int32.MinValue;

            if (ddlLastVisit.SelectedIndex > 0)
                pole.LVisit = new DateTime(Convert.ToInt32(ddlLastVisit.SelectedItem), 1, 1);
            else
                pole.LVisit = DateTime.MinValue;

            pole.Comments = txtComments.Text.Trim();
            pole.Images = camControl.GetTakenImages();

            foreach (EImage image in pole.Images)
                image.ImageType = ImageType.Pole;

            pole.Notes = assignNotes1.GetSelectedValues();
            pole.InspectionType = ddlInspection.SelectedItem as ELookUp;
            pole.ResultType = ddlResult.SelectedItem as ELookUp;
            pole.isElectrical = chkElectrical.Checked;
            pole.GroundWireRepair = chkGWRepair.Checked;
            pole.PoleTag = chkPoleTagId.Checked;
            pole.Billable = chkBillable.Checked;

            if (ddlGuardsQuantity.SelectedIndex > 0)
                pole.GuardsQuantity = (int)ddlGuardsQuantity.SelectedItem;
            else
                pole.GuardsQuantity = Int32.MinValue;

            switch(Mode)
            {
                case EditorMode.Duplicate:
                case EditorMode.New:
                    LPole.Save(pole);
                    break;
                case EditorMode.Update:
                    pole.Id = PoleToBeLoaded.Id;
                    LPole.Update(pole);
                    break;
            }
        }

        public void LoadPole(EPole pole)
        {
            //Get de pole inspection from database
            pole = LPole.GetById(pole);
            PoleToBeLoaded = pole;

            //Set the controls
            MobileUIHelper.SelectItem(ddlClasses, pole.Class);
            MobileUIHelper.SelectItem(ddlInspection, pole.InspectionType);
            MobileUIHelper.SelectItem(ddlLengths, pole.Length);
            MobileUIHelper.SelectItem(ddlResult, pole.ResultType);
            MobileUIHelper.SelectItem(ddlSpecies, pole.Specie);
            MobileUIHelper.SelectItem(ddlTreatments, pole.Treatment);
            MobileUIHelper.SelectItem(ddlKv, pole.Kv);
            MobileUIHelper.SelectItem(ddlACSR, pole.ACSR);
            MobileUIHelper.SelectItem(ddlConductorType, pole.ConductorType);

            ddlYears.SelectedItem = pole.Year;
            
            if (pole.LVisit != DateTime.MinValue) 
                ddlLastVisit.SelectedItem = pole.LVisit.Year;

            if (Mode != EditorMode.Duplicate) 
            {
                camControl.SetTakenImages(pole.Images);
                camControl.SelectPicture(0);
            }

            if (pole.Latitude != Double.MinValue && pole.Longitude != Double.MinValue)
                pGPSViewer.SetPosition(pole.Latitude, pole.Longitude);

            if (pole.GuardsQuantity == int.MinValue || pole.GuardsQuantity == 0)
            {
                ddlGuardsQuantity.SelectedIndex = 0;
                chkGuards.Checked = false;
            }
            else
            {
                ddlGuardsQuantity.SelectedItem = pole.GuardsQuantity;
                chkGuards.Checked = true;
            }
            chkGWRepair.Checked = pole.GroundWireRepair;
            chkPoleTagId.Checked = pole.PoleTag;
            chkBillable.Checked = pole.Billable;

            arTop.Load(pole.Tops);
            arPhase.Load(pole.Phases);

            ddlMapSection.SetValues(pole);
            assignNotes1.SetSelectedValues(pole.Notes);

            txtCircuit.Text = pole.Circuit;
            txtComments.Text = pole.Comments;
            chkElectrical.Checked = pole.isElectrical;

            txtInspBy.Text = pole.InspBy;
            txtNumber.Text = pole.Number;
        }

        public void ResetControls()
        {
            if (ddlClasses.Items.Count > 0)
                ddlClasses.SelectedIndex = 0;

            if (ddlInspection.Items.Count > 0)
                ddlInspection.SelectedIndex = 0;

            if (ddlLengths.Items.Count > 0)
                ddlLengths.SelectedIndex = 0;

            if (ddlResult.Items.Count > 0)
                ddlResult.SelectedIndex = 0;

            if (ddlSpecies.Items.Count > 0)
                ddlSpecies.SelectedIndex = 0;

            if (ddlTreatments.Items.Count > 0)
                ddlTreatments.SelectedIndex = 0;

            if (ddlYears.Items.Count > 0)
                ddlYears.SelectedIndex = 0;

            if (ddlLastVisit.Items.Count > 0)
                ddlLastVisit.SelectedIndex = 0;

            if (ddlKv.Items.Count > 0)
                ddlKv.SelectedIndex = 0;

            if (ddlConductorType.Items.Count > 0)
                ddlConductorType.SelectedIndex = 0;

            if (ddlACSR.Items.Count > 0)
                ddlACSR.SelectedIndex = 0;

            ddlMapSection.Reset();

            arTop.Reset();
            arPhase.Reset();

            pGPSViewer.Refresh();

            assignNotes1.Reset();

            chkElectrical.Checked = false;

            txtComments.Text = string.Empty;
            txtInspBy.Text = string.Empty;
            txtNumber.Text = string.Empty;
            txtCircuit.Text = string.Empty;
            chkPoleTagId.Checked = false;
            chkGWRepair.Checked = false;
            chkBillable.Checked = false;
            chkGuards.Checked = false;
            ddlGuardsQuantity.Enabled = false;

            camControl.Reset();

            tbcDistribution.SelectedIndex = 0;
        }

        #endregion

        private void chkGuards_CheckStateChanged(object sender, EventArgs e)
        {
            ddlGuardsQuantity.Enabled = chkGuards.Checked;

            if (!chkGuards.Checked)
                ddlGuardsQuantity.SelectedIndex = 0;
        }


    }
}